<script setup lang="ts">
import {
  ElAutocomplete,
  ElCol,
  ElDialog,
  ElDivider,
  ElMenu,
  ElMenuItem,
  ElMessage,
  ElRow,
  ElScrollbar,
  ElTag
} from 'element-plus'
import { propTypes } from '@/utils/propTypes'
import 'element-plus/es/components/icon/style/css'
import 'element-plus/es/components/input/style/css'
import 'element-plus/es/components/button/style/css'
import 'element-plus/es/components/tag/style/css'
import 'element-plus/es/components/menu/style/css'
import 'element-plus/es/components/menu-item/style/css'
import { Search } from '@element-plus/icons-vue'
import { computed, onUpdated, reactive, ref, useAttrs } from 'vue'
import type { Ref } from 'vue'

interface Menu {
  code: string
  name: string
  parent?: string
  selected?: boolean
}

type MenuKey = 'first' | 'second' | 'third' | 'fourth'

interface Selections {
  // 国家
  first: Menu[]
}

const props = defineProps({
  data: propTypes.object.def({} as Selections),
  limit: propTypes.number.def(5),
  modelValue: propTypes.bool.def(false)
})

const emits = defineEmits(['update:modelValue', 'ok'])

const getBindValue = computed(() => {
  const attrs = useAttrs()
  return { ...attrs, ...props }
})

// 增加这个reactive以存储和管理状态
const state = reactive<{ selectedList: Menu[] }>({
  selectedList: [
    // { [parentCode: string]: code[] }
  ]
})

const first = ref<Menu[]>([])
const second = ref<Menu[]>([])
const third = ref<Menu[]>([])
const fourth = ref<Menu[]>([])
const searchText = ref<string>('')
const keys = ref<string[]>(['first', 'second', 'third', 'fourth'])

const records = ref<Menu[]>([])
const querySearch = (queryString: string, cb: any) => {
  const results = queryString ? records.value.filter(createFilter(queryString)) : records.value
  cb(results)
}
const createFilter = (queryString: string) => {
  return (record: Menu) => {
    return record.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}

// 深拷贝函数
function copyDeep(obj: any) {
  // 如果不是对象或者为 null，直接返回该值（递归基）
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }

  // 初始化一个新数组或对象，来存放深复制的值
  let copy = Array.isArray(obj) ? [] : {}

  // 遍历对象或数组中的每个项
  for (let key in obj) {
    // 确保key是对象自身的属性而不是原型链上的
    if (obj.hasOwnProperty(key)) {
      // 递归复制每一项的值
      copy[key] = copyDeep(obj[key])
    }
  }

  return copy
}

const initData = () => {
  // console.log(props.data?.first)/
  first.value = copyDeep(props.data?.first || [])

  // 遍历 first 数组，检查 selected 属性
  first.value.forEach((item: Menu) => {
    if (item.selected) {
      // 如果 selected 为 true，则添加到 selectedList 中
      state.selectedList.push(item)
    }
  })
}

onUpdated(() => {
  initData()
  records.value = copyDeep(props.data?.first || [])
})

// const handleSelect = (item: Menu) => {
//   // 首先取消所有菜单项的选中状态
//   first.value.forEach((menu: Menu) => {
//     menu.selected = false
//   })

//   // 然后找到被点击的菜单项，并将其设置为选中状态
//   const selectedItem = first.value.find((menu: Menu) => menu.code === item.code)

//   if (selectedItem) {
//     selectedItem.selected = true
//     handleMenuSelect(selectedItem, 'first', true)
//     console.log(selectedItem)
//   }
// }

const handleSelect = (item: Menu) => {
  first.value.forEach((item: Menu) => {
    item.selected = false
  })
  let results = findParent(item.code, 'fourth').reverse()
  results[0].selected = true
  const copyCountries = copyDeep(first.value)
  first.value = []
  copyCountries.forEach((m: Menu) => {
    m.selected = m.code === item.parent
  })
  first.value = copyCountries
  console.log(111, first.value)
  results.push(item)
  results.forEach((item, index) => {
    item.selected = false
    handleMenuSelect(item, keys.value[index] as MenuKey, results.length - 1 === index)
  })
  first.value.forEach((m: Menu) => {
    m.code !== item.code
  })
}

const getMenuSelectionByKey = (type: MenuKey) => {
  return {
    first: first,
    second: second,
    third: third,
    fourth: fourth
  }[type] as Ref<Menu[]>
}

const setSelected = (selection: Ref<Menu[]>, bool: boolean, code?: string) => {
  selection.value.forEach((item: Menu) => {
    if (code && item.code === code) {
      console.log(item)
      item.selected = bool
      console.log(item)
    }
  })
}

const handleTagClose = (item: Menu) => {
  const index = state.selectedList.findIndex((m) => m.code === item.code)
  console.log('111111111111', index)
  state.selectedList.splice(index, 1)
  console.log('22222', state.selectedList)
  console.log('333333', item.code)

  setSelected(first, false, item.code)
}

const handleMenuSelect = (item: Menu, menuKey: MenuKey, flag = false) => {
  if (state.selectedList.length >= props.limit) {
    ElMessage.warning('选择数量已达上限')
    return
  }
  console.log(flag)
  const menuSelection = getMenuSelectionByKey(menuKey)

  const index = menuSelection.value?.findIndex((m) => m.code === item.code)
  if (index !== -1) {
    // 切换选中状态
    menuSelection.value[index].selected = !menuSelection.value[index].selected

    // 更新selectedList
    const selectedIndex = state.selectedList.findIndex(
      (selectedItem) => selectedItem.code === item.code
    )

    // if (menuKey === 'fourth' || flag) {
    if (selectedIndex === -1 && menuSelection.value[index]?.selected) {
      state.selectedList.push(item)
    } else if (selectedIndex !== -1 && !menuSelection.value[index].selected) {
      state.selectedList.splice(selectedIndex, 1)
    }
    // }
  }

  // const menuIndex = keys.value.findIndex((key) => key === menuKey)
  // const key = keys.value[menuIndex] as MenuKey
  // if (key === 'first') {
  //   // second
  //   second.value = props.data.second.filter((m: Menu) => m.parent === item.code)
  //   // third
  //   const second = second.value[0]
  //   third.value = props.data.third.filter((m: Menu) => m.parent === second.code)
  //   // fourth
  //   const city = third.value[0]
  //   fourth.value = props.data.fourth.filter((m: Menu) => m.parent === city.code)
  // } else if (key === 'second') {
  //   third.value = props.data.third.filter((m: Menu) => m.parent === item.code)
  //   const city = third.value[0]
  //   fourth.value = props.data.fourth.filter((m: Menu) => m.parent === city.code)
  // } else if (key === 'third') {
  //   fourth.value = props.data.fourth.filter((m: Menu) => m.parent === item.code)
  // }
}

function findParent(code: string, level: string) {
  let parentCode: string | undefined = ''
  let result: Menu | any = null

  switch (level) {
    case 'fourth':
      // 查找地区的父级（城市）
      parentCode = props.data.fourth.find((district) => district.code === code)?.parent
      result = props.data.third.find((city) => city.code === parentCode)
      if (result) return [result, ...findParent(result.code, 'third')]
      break
    case 'third':
      // 查找城市的父级（省份）
      parentCode = props.data.third.find((city) => city.code === code)?.parent
      result = props.data.seconds.find((second) => second.code === parentCode)
      if (result) return [result, ...findParent(result.code, 'seconds')]
      break
    case 'seconds':
      // 查找省份的父级（国家）
      parentCode = props.data.seconds.find((second) => second.code === code)?.parent
      result = props.data.first.find((first) => first.code === parentCode)
      if (result) return [result] // 国家是最顶级，没有父级
      break
  }
  return [] // 如果没有找到父级，返回空数组
}

function closeDialog() {
  emits('update:modelValue', false)
}

const handleClose = () => {
  closeDialog()
}

const handleSubmit = async () => {
  // 提交逻辑处理
  console.log('已选择项：', state.selectedList)
  if (state.selectedList.length === 0) {
    ElMessage.warning('请至少选择一个选项')
    return
  }
  console.log('state.selectedList: ', state.selectedList)
  const result: string[] = []
  state.selectedList.forEach((item) => {
    result.push(item.code)
  })
  console.log('result: ', result)
  emits('ok', result)
  handleClose()
}
</script>

<template>
  <ElDialog
    class="!rounded-lg !p-0"
    v-bind="getBindValue"
    destroy-on-close
    lock-scroll
    draggable
    :close-on-click-modal="false"
    :show-close="false"
  >
    <template #header="{ close }">
      <div class="flex justify-between items-center h-70px px-30px relative">
        <slot name="title">
          <div class="flex items-center">
            <div class="w-92px text-l font-bold">选择</div>
            <ElAutocomplete
              v-model="searchText"
              :fetch-suggestions="querySearch"
              clearable
              :prefix-icon="Search"
              class="search-input"
              placeholder="搜索"
              @select="handleSelect"
            >
              <template #default="{ item }">
                <div class="value">{{ item.name }}</div>
              </template>
            </ElAutocomplete>
          </div>
        </slot>
        <div
          class="h-54px flex justify-between items-center absolute top-[50%] right-15px translate-y-[-50%]"
        >
          <Icon
            class="cursor-pointer is-hover !h-54px"
            icon="vi-ep:close"
            hover-color="var(--el-color-primary)"
            color="var(--el-color-info)"
            @click="close"
          />
        </div>
      </div>
    </template>

    <div class="h-70px flex items-center px-30px">
      <span class="font-bold block"
        >已选 ({{ state.selectedList.length }}/{{ getBindValue.limit }})</span
      >
      <ElTag
        class="ml-2 !py-15px cursor-pointer"
        v-for="(item, index) in state.selectedList"
        :key="index"
        closable
        :class="{ '!ml-4': index === 0 }"
        @close="() => handleTagClose(item)"
      >
        {{ item.name }}
      </ElTag>
    </div>
    <ElDivider class="w-full !my-0 !-mb-1px" />

    <el-row class="flex">
      <el-col class="menu1 w-full" style="border-right: 1px solid var(--el-border-color)">
        <ElScrollbar>
          <div class="h-360px">
            <el-menu class="h-fit !border-0">
              <template v-if="first.length">
                <el-menu-item
                  v-for="item in first"
                  :key="item.code"
                  :index="item.code"
                  :class="{ 'is-selected': item.selected }"
                  @click="() => handleMenuSelect(item, 'first')"
                >
                  <span class="pl-10px">{{ item.name }}</span>
                </el-menu-item>
              </template>
            </el-menu>
          </div>
        </ElScrollbar>
      </el-col>

      <!-- 子菜单 -->
    </el-row>

    <template #footer>
      <BaseButton class="w-74px" type="primary" @click="handleSubmit">确定</BaseButton>
      <BaseButton class="w-74px" @click="handleClose">取消</BaseButton>
    </template>
  </ElDialog>
</template>

<style lang="less">
.@{elNamespace}-overlay-dialog {
  display: flex;
  justify-content: center;
  align-items: center;
}

.@{elNamespace}-dialog {
  margin: 0 !important;

  &__header {
    height: 70px;
    padding: 0;
    margin-right: 0 !important;
    border-bottom: 1px solid var(--el-border-color);
  }

  &__body {
    padding: 0 !important;
  }

  &__footer {
    height: 70px;
    padding-right: 30px;
    border-top: 1px solid var(--el-border-color);
  }

  &__headerbtn {
    top: 0;
  }
}

.search-input {
  margin-left: 15px;

  .el-input__wrapper {
    border-radius: 15px !important;
  }
}

.el-menu-item.is-active {
  color: var(--el-menu-text-color);
  background-color: white;
}

.menu1 {
  .el-menu-item.is-active {
    color: var(--el-menu-active-color);
    background-color: var(--el-menu-hover-bg-color);
  }
}

.el-menu-item.is-selected {
  color: var(--el-menu-active-color);
  background-color: var(--el-menu-hover-bg-color);
}
</style>
